package com.wl.shixun4.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wl.shixun4.dao.ProductDAO;
import com.wl.shixun4.entity.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品数据表格Servlet - 实训任务四
 * 处理数据表格的AJAX请求，支持过滤、排序、分页
 */
@WebServlet("/shixun4/productDataTable")
public class ProductDataTableServlet extends HttpServlet {
    
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        try {
            // 获取分页参数
            int page = getIntParameter(request, "page", 1);
            int pageSize = getIntParameter(request, "pageSize", 10);
            
            // 获取过滤参数
            List<ProductDAO.FilterInfo> filters = parseFilters(request);
            
            // 获取排序参数
            List<ProductDAO.SortInfo> sorts = parseSorts(request);
            
            // 执行查询
            ProductDAO.QueryResult result = ProductDAO.advancedQuery(filters, sorts, page, pageSize);
            
            // 构建响应数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("success", true);
            responseData.put("data", convertProductsToMap(result.getProducts()));
            responseData.put("totalCount", result.getTotalCount());
            responseData.put("currentPage", result.getCurrentPage());
            responseData.put("pageSize", result.getPageSize());
            responseData.put("totalPages", result.getTotalPages());
            
            // 返回JSON响应
            PrintWriter out = response.getWriter();
            out.print(objectMapper.writeValueAsString(responseData));
            out.flush();
            
        } catch (Exception e) {
            // 错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            
            PrintWriter out = response.getWriter();
            out.print(objectMapper.writeValueAsString(errorResponse));
            out.flush();
        }
    }
    
    /**
     * 解析过滤参数
     */
    private List<ProductDAO.FilterInfo> parseFilters(HttpServletRequest request) {
        List<ProductDAO.FilterInfo> filters = new ArrayList<>();
        
        // 单字段过滤
        String filterColumn = request.getParameter("filterColumn");
        String filterValue = request.getParameter("filterValue");
        String filterOperator = request.getParameter("filterOperator");
        
        if (filterColumn != null && !filterColumn.trim().isEmpty() && 
            filterValue != null && !filterValue.trim().isEmpty()) {
            String operator = (filterOperator != null && !filterOperator.trim().isEmpty()) ? 
                             filterOperator : "LIKE";
            filters.add(new ProductDAO.FilterInfo(filterColumn, operator, filterValue));
        }
        
        // 多字段过滤 (支持filter1, filter2, filter3等)
        for (int i = 1; i <= 10; i++) {
            String column = request.getParameter("filter" + i + "Column");
            String value = request.getParameter("filter" + i + "Value");
            String operator = request.getParameter("filter" + i + "Operator");
            String value2 = request.getParameter("filter" + i + "Value2");
            
            if (column != null && !column.trim().isEmpty() && 
                value != null && !value.trim().isEmpty()) {
                String op = (operator != null && !operator.trim().isEmpty()) ? operator : "LIKE";
                
                if ("BETWEEN".equalsIgnoreCase(op) && value2 != null && !value2.trim().isEmpty()) {
                    filters.add(new ProductDAO.FilterInfo(column, op, value, value2));
                } else {
                    filters.add(new ProductDAO.FilterInfo(column, op, value));
                }
            }
        }
        
        return filters;
    }
    
    /**
     * 解析排序参数
     */
    private List<ProductDAO.SortInfo> parseSorts(HttpServletRequest request) {
        List<ProductDAO.SortInfo> sorts = new ArrayList<>();
        
        // 单字段排序
        String sortColumn = request.getParameter("sortColumn");
        String sortDirection = request.getParameter("sortDirection");
        
        if (sortColumn != null && !sortColumn.trim().isEmpty()) {
            String direction = (sortDirection != null && sortDirection.equalsIgnoreCase("DESC")) ? 
                              "DESC" : "ASC";
            sorts.add(new ProductDAO.SortInfo(sortColumn, direction, 1));
        }
        
        // 多字段排序 (支持sort1, sort2, sort3等)
        for (int i = 1; i <= 5; i++) {
            String column = request.getParameter("sort" + i + "Column");
            String direction = request.getParameter("sort" + i + "Direction");
            
            if (column != null && !column.trim().isEmpty()) {
                String dir = (direction != null && direction.equalsIgnoreCase("DESC")) ? "DESC" : "ASC";
                sorts.add(new ProductDAO.SortInfo(column, dir, i));
            }
        }
        
        return sorts;
    }
    
    /**
     * 将Product对象列表转换为Map列表（用于JSON序列化）
     */
    private List<Map<String, Object>> convertProductsToMap(List<Product> products) {
        List<Map<String, Object>> result = new ArrayList<>();
        
        for (Product product : products) {
            Map<String, Object> productMap = new HashMap<>();
            productMap.put("id", product.getId());
            productMap.put("number", product.getNumber());
            productMap.put("name", product.getName());
            productMap.put("price", product.getPrice());
            productMap.put("madetime", product.getMadetime() != null ? 
                          product.getMadetime().toString() : null);
            result.add(productMap);
        }
        
        return result;
    }
    
    /**
     * 获取整数参数，带默认值
     */
    private int getIntParameter(HttpServletRequest request, String paramName, int defaultValue) {
        String paramValue = request.getParameter(paramName);
        if (paramValue != null && !paramValue.trim().isEmpty()) {
            try {
                return Integer.parseInt(paramValue.trim());
            } catch (NumberFormatException e) {
                // 忽略格式错误，返回默认值
            }
        }
        return defaultValue;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        try {
            String action = request.getParameter("action");
            Map<String, Object> responseData = new HashMap<>();

            if ("create".equals(action)) {
                // 创建新记录
                Product product = new Product();
                product.setName(request.getParameter("name"));
                product.setNumber(request.getParameter("number"));
                product.setPrice(request.getParameter("price"));

                // 解析日期
                String dateStr = request.getParameter("madetime");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Timestamp timestamp = new Timestamp(sdf.parse(dateStr).getTime());
                product.setMadetime(timestamp);

                boolean success = ProductDAO.insert(product);
                responseData.put("success", success);
                responseData.put("message", success ? "记录创建成功" : "记录创建失败");

            } else if ("update".equals(action)) {
                // 更新记录
                long id = Long.parseLong(request.getParameter("id"));
                Product product = new Product();
                product.setId(id);
                product.setName(request.getParameter("name"));
                product.setNumber(request.getParameter("number"));
                product.setPrice(request.getParameter("price"));

                // 解析日期
                String dateStr = request.getParameter("madetime");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Timestamp timestamp = new Timestamp(sdf.parse(dateStr).getTime());
                product.setMadetime(timestamp);

                boolean success = ProductDAO.update(product);
                responseData.put("success", success);
                responseData.put("message", success ? "记录更新成功" : "记录更新失败");

            } else if ("delete".equals(action)) {
                // 删除记录
                long id = Long.parseLong(request.getParameter("id"));
                boolean success = ProductDAO.delete(id);
                responseData.put("success", success);
                responseData.put("message", success ? "记录删除成功" : "记录删除失败");

            } else {
                responseData.put("success", false);
                responseData.put("message", "未知操作: " + action);
            }

            // 返回JSON响应
            PrintWriter out = response.getWriter();
            out.print(objectMapper.writeValueAsString(responseData));
            out.flush();

        } catch (Exception e) {
            // 错误响应
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "操作失败: " + e.getMessage());

            PrintWriter out = response.getWriter();
            out.print(objectMapper.writeValueAsString(errorResponse));
            out.flush();
        }
    }
}
